package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.base.domain.Answer;
import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.QuestionQueryObject;
import cn.wolfcode.trip.base.service.IAnswerService;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.JsonResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("questions")
public class QuestionController {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IAnswerService answerService;

    /**
     * 保存提问记录
     *
     * @param question
     * @return
     */
    @PostMapping("{questionId}")
    public JsonResult save(Question question) {
        JsonResult result = new JsonResult();
        questionService.saveOrUpdate(question);
        result.setErrorMsg("提问完成,请等待骡友回答...");
        return result;
    }

    /**
     * 查询当前用户提过的问题
     *
     * @param userId
     * @return 我的提问列表
     */
    @GetMapping("/{userId}")
    public List<Question> getMyQuestions(@PathVariable Long userId) {
        if (userId != null) {
            return questionService.listByUserId(userId);
        }
        return null;

    }

    /**
     * 查询单个问题
     *
     * @param id
     * @return 当前问题
     */
    @GetMapping("/{id}/question")
    public Question getQuestion(@PathVariable Long id) {
        if (id != null) {
            return questionService.get(id);
        }

        return null;

    }

    /**
     * 查询当前单个问题的评论(连中间表)
     *
     * @param questionId 当前问题的 id
     * @return 当前问题
     */
    @GetMapping("/{questionId}/answers")
    public PageInfo getAnswerByQuestionId(QuestionQueryObject qo) {
        qo.setOrderBy("answerTime desc");
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());

        List<Answer> list = answerService.queryForList(qo);
        return new PageInfo(list);


    }

    /**
     * 公共问题列表
     *
     * @return
     */
    @GetMapping
    public PageInfo<Question> askQuestion(QuestionQueryObject qo) {
        qo.setOrderBy("askTime DESC");  //最新提问的排在前面
        return questionService.query(qo);


    }
}
